<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { type OptionType } from '../types/index'

const props = defineProps({
  options: {
    type: Array as () => OptionType[],
    required: true
  },
  active: {
    type: Boolean,
    default: false
  },
  defaultActiveIndex: {
    type: Number,
    default: 0
  }
})

const activeIndex = ref(props.defaultActiveIndex)

watch(
  () => props.active,
  (isActive) => {
    if (isActive) {
      window.addEventListener('keydown', handleKeydown)
    } else {
      window.removeEventListener('keydown', handleKeydown)
    }
  }
)

const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'ArrowUp') {
    activeIndex.value = (activeIndex.value - 1 + props.options.length) % props.options.length
  } else if (event.key === 'ArrowDown') {
    activeIndex.value = (activeIndex.value + 1 + props.options.length) % props.options.length
  } else if (event.key === 'Enter') {
    props.options[activeIndex.value].action()
  }
}


onMounted(() => {
  if (props.active) {
    window.addEventListener('keydown', handleKeydown)
  }
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeydown)
})
</script>

<template>
  <div class="options">
    <p
      class="options-line"
      :class="{
        'active': index === activeIndex
      }"
      v-for="(option, index) in options"
      :key="index"
    >
      {{ option.text }}
    </p>
  </div>
</template>

<style lang="scss">
.options {
  margin-top: 8px;
  .options-line {
    margin-bottom: 8px;
    margin-left: -16px;
    &::before {
      content: '';
      display: inline-block;
      width: 6px;
      height: 6px;
      border-style: solid;
      border-width: 2px 2px 0 0;
      border-color: transparent;
      transform: rotate(45deg);
      margin-right: 8px;
    }
    &.active::before {
      border-color: white;
    }
  }
}
</style>

